using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;
public class TwitterFetch : MonoBehaviour 
{
private string m_sWebData;// = "31,steveemmerich,#1234,#heart,message \n" +
								//"32,steveemm,#4321,#gun,messsdfja93h4bauodfaf,;s'mdfijahgv./ \n";
	private string m_sURLReset = "http://heartdropper.com/?service=reset";
   private string m_sURLFetch = "http://heartdropper.com/?service=fetch&request[id]=";
   private string m_sURLFetchBase = "http://heartdropper.com/?service=fetch&request[id]=";
	private string m_sURLImageBase = "http://heartdropper.com/?service=avatar&request[username]=";
	public float m_fTimeToGrab = 1.0f;
     private float m_fTimer = 0.0f;
	private Rect textrect = new Rect (10, 150, 500, 500);
	  private int m_nLastTweetId = 0;
   List<List<string>> ParsedData = new List< List<string>>();
    private WWW m_wWebObject;
	public Transform m_tImagePlacement;
	
	void Awake()
	{
		 m_sURLFetch =  m_sURLFetchBase + m_nLastTweetId;
	}
	// Use this for initialization
	void Start () 
	{
	//ParseData(m_sWebData);
		StartCoroutine("ResetData");
		//StartCoroutine("FetchTexture", "steveemmerich");
	}
	
	// Update is called once per frame
	void Update () 
	{
		
		if(m_wWebObject.isDone)
    	{
			if(m_fTimer >= m_fTimeToGrab )
    		{
				//Debug.Log("Fetching");
    			m_fTimer = 0.0f;
	   			StartCoroutine("FetchData");
				
		    }
	    	else
	    	{
	    		m_fTimer += Time.deltaTime;
	    	}
		}
		else
        {
       		 Debug.Log("Still Downloading " + m_wWebObject.isDone + m_wWebObject.progress + "%");
        }
	}
	
    void ParseData(string _data)
    {	
//		Debug.Log(_data);
		if(_data != "")
		{

            for(int i = 0; i < ParsedData.Count; ++i)
			{
			ParsedData[i].Clear();
			}
			ParsedData.Clear();
                   	
			List<string> _templist = new List<string>();
		
	          foreach(string _s in _data.Split("\n".ToCharArray(), System.StringSplitOptions.None))
	          {
				foreach(string _ss in _s.Split(",".ToCharArray(),5))
				{
					
					  	_templist.Add(_ss);		
				}
				ParsedData.Add(_templist);
	          }
			int lastindex = ParsedData.Count-1;
		
			m_nLastTweetId = Int32.Parse(ParsedData[lastindex][0]);
		 	m_sURLFetch = m_sURLFetchBase + m_nLastTweetId;
		
			SendMessages(ParsedData);
		
		}
		
    }
	IEnumerator FetchData()
	{
		
		//Debug.Log("In Fetch Data");
    		m_wWebObject.Dispose();
    	 	m_wWebObject = new WWW(m_sURLFetch); //here we create a var called 'w' and we sync with our URL and the form
        	yield return m_wWebObject; //we wait for the form to check the PHP file, so our game dont just hang
        	//Debug.Log(m_wWebObject.size);
			if (m_wWebObject.error != null) 
			{
            	print(m_wWebObject.error); //if there is an error, tell us
				return true;
        	} 
			else if(m_wWebObject.size > 0)
			{
            	//print("Test ok");
				ParseData(m_wWebObject.text);
        	}
			else
			{
				Debug.Log("No Data Right now");
			}
        
        
	}
	IEnumerator ResetData()
	{
			m_wWebObject = new WWW(m_sURLReset); //here we create a var called 'w' and we sync with our URL and the form
        	yield return m_wWebObject; //we wait for the form to check the PHP file, so our game dont just hang
        	if (m_wWebObject.error != null) 
			{
            	print(m_wWebObject.error); //if there is an error, tell us
        	} 
			else 
			{
            	//print("Test ok");
				ParseData(m_wWebObject.text);
        	}	
	}
	
	IEnumerator DownloadTexture(string _username)
	{ 	
		//Debug.Log("Getting Texture");
		 _username = "steveemmerich";
		string URL = m_sURLImageBase + _username;
		m_tImagePlacement.renderer.material.mainTexture = new Texture2D(4, 4, TextureFormat.DXT1, false);
					Debug.Log(URL);
		while(true)
		{
			m_wWebObject = new WWW(URL); //here we create a var called 'w' and we sync with our URL and the form
        	//Debug.Log("Still Downloading " + m_wWebObject.isDone + m_wWebObject.progress + "%");
			yield return m_wWebObject; //we wait for the form to check the PHP file, so our game dont just hang
        	//Debug.Log("Still Downloading " + m_wWebObject.isDone + m_wWebObject.progress + "%");
			
			if (m_wWebObject.error != null) 
			{
            	print(m_wWebObject.error); //if there is an error, tell us
        	} 
			else 
			{
            	//print("Test ok");
			
		    	// Create a texture in DXT1 format
				if(m_tImagePlacement)
				{
   			 		m_wWebObject.LoadImageIntoTexture((Texture2D)m_tImagePlacement.renderer.material.mainTexture);
				}
				else
				{
					Debug.LogError("No place for the image");
				}// assign the downloaded image to the main texture of the object
       			 
			}
		}
	}
	void OnGUI()
	{
		string formText = "";
		for(int i = 0; i < ParsedData.Count-1; ++i)
		{
			for( int j = 0; j < ParsedData[i].Count-1; ++j)
			{
				formText += ParsedData[i][j];
	    		//Debug.Log(ParsedData[i][j]);
			}
		}
		 GUI.TextArea( textrect, formText );

	}
	void SendMessages(List<List<string>> _messageData)
    {
    /*****************************************/
    /*             message data              */
    /*  0 = message                          */
    /*  1 = Location                         */
    /*  2 = Other Data                       */
    /*****************************************/
//		Debug.Log(ParseData[0]);
  /*  Debug.Log(_messageData[0][0]);
		Debug.Log(_messageData[0][1]);
		Debug.Log(_messageData[0][2]);
		Debug.Log(_messageData[0][3]);*/
   for( int i = 0; i < _messageData.Count; ++i)
    {
			
      	switch(_messageData[i][3].ToLower())
      	{
      	case "heart":
      	{
				Debug.Log("Sending Heart" + _messageData[i][2]);
      	Messenger<string>.Invoke("heart",_messageData[i][2]);
      	break;
      	}
      	case "ammo":
      	{
      		Messenger<string>.Invoke("ammo",_messageData[i][2]);
      	break;
      	}
      	case "dance":
      	{
      		Messenger<string>.Invoke("dance",_messageData[i][2]);
      	break;
      	}
      	case "lowerbridge":
      	{
      		Messenger<string>.Invoke("lowerbridge",_messageData[i][2]);
      	break;
      	}
      	case "raisebridge":
      	{
      		Messenger<string>.Invoke("raisebridge",_messageData[i][2]);
      	break;
      	}
      	case "opendoor":
      	{
      		Messenger<string>.Invoke("opendoor",_messageData[i][2]);
      	break;
      	}
      	case "closedoor":
      	{
      		Messenger<string>.Invoke("closedoor",_messageData[i][2]);
      	break;
      	}
		case "speed":
      	{
      		Messenger<string>.Invoke("speed",_messageData[i][2]);
      	break;
      	}
      	
      	}
      }
	}


}
